package com.kcloud.commons.authorization.settings.biz.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kcloud.commons.entity.control.AttributeGroup;
import com.kcloud.commons.entity.control.Operation;
import lombok.Data;

import java.util.Arrays;
import java.util.List;

/**
 * @author songhuiqing
 */
@Data
public class BaseClob {
    private String operationText; //操作json字符串
    private String attributeText; // 属性配置json字符串

    @TableField(exist = false)
    private List<Operation> operations; // 操作清单

    @TableField(exist = false)
    private List<AttributeGroup> attributeGroups; // 属性集清单

    public List<Operation> getOperations(){
        if (this.operations != null) {
            return this.operations;
        }
        if(operationText != null && !"".equals(operationText)) {
            try {
                Operation[] arr = new ObjectMapper().readValue(operationText, Operation[].class);
                this.operations = Arrays.asList(arr);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return this.operations;
    }

    public List<AttributeGroup> getAttributeGroups() {
        if (this.attributeGroups != null) {
            return this.attributeGroups;
        }
        if(attributeText != null && !"".equals(attributeText)) {
            try {
                AttributeGroup[] attrs = new ObjectMapper().readValue(attributeText, AttributeGroup[].class);
                this.attributeGroups = Arrays.asList(attrs);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return this.attributeGroups;
    }

    public String getOperationText() {
        if(operationText != null && !"".equals(operationText)) {
            return operationText;
        }
        if(operations != null && operations.size() !=0) {
            String text = "";
            try {
                text = new ObjectMapper().writeValueAsString(operations);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return text;
        }
        return operationText;
    }

    public String getAttributeText() {
        if(attributeText != null && !"".equals(attributeText)) {
            return attributeText;
        }
        if(attributeGroups != null && attributeGroups.size() !=0) {
            String text = "";
            try {
                text = new ObjectMapper().writeValueAsString(attributeGroups);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return text;
        }
        return attributeText;
    }
}
